import os
import shutil

def split_numeric_folders(src_dir, dst_dir, batch_size=10):
    """
    将数字命名的文件夹按批次分组到新目录
    参数：
        src_dir: 包含数字文件夹的源目录（例如：download目录）
        dst_dir: 结果目录
        batch_size: 每个新目录包含的文件夹数量（默认50）
    返回：
        包含 (新目录路径, 移动的文件夹数量) 的元组列表
    """
    # 获取所有数字文件夹并排序
    folders = []
    for name in os.listdir(src_dir):

        path = os.path.join(src_dir, name)
        if os.path.isdir(path) and name.isdigit():
            folders.append((int(name), path))
    
    if not folders:
        raise ValueError("未找到数字命名的文件夹")
    
    # 按数字排序
    folders.sort()
    sorted_numbers = [f[0] for f in folders]
    sorted_paths = [f[1] for f in folders]
    #print(sorted_numbers)
    #print(sorted_paths)
    
    
    batches = []
    
    # 按批次处理
    for i in range(0, len(sorted_paths), batch_size):
        batch_paths = sorted_paths[i:i+batch_size]
        batch_numbers = sorted_numbers[i:i+batch_size]
        
        # 创建新目录（使用本批次最小数字）
        new_dir_name = str(batch_numbers[0])
        new_dir_path = os.path.join(dst_dir, new_dir_name)
        os.makedirs(new_dir_path, exist_ok=True)
        
        # 移动文件夹
        moved_count = 0
        for folder_path in batch_paths:
            try:
                folder_name = os.path.basename(folder_path)
                dest_path = os.path.join(new_dir_path, folder_name)
                shutil.move(folder_path, dest_path)
                moved_count += 1
            except Exception as e:
                print(f"移动失败 [{folder_path}]: {str(e)}")
        
        batches.append((new_dir_path, moved_count))
    
    return batches

if __name__ == '__main__':
    src_dir = "F://download//tg"
    dst_dir = "f://download"
    try:
        results = split_numeric_folders(src_dir, dst_dir)
        print(f"操作完成，共创建 {len(results)} 个新目录：")
        for new_dir, count in results:
            print(f"· {os.path.basename(new_dir)} 目录包含 {count} 个文件夹")
    except Exception as e:
        print(f"操作失败: {str(e)}")